package lhy.autoparts.servlet;

import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lhy.autoparts.SharedConstant;
import lhy.orm.dao.DatabaseConnector;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.Objects;


@WebServlet("/IdNameQueryServlet")
public class IdNameQueryServlet extends Utf8Servlet {

    private static final Map<IdTableQuery,String> idTableNameMap = new Object2ObjectArrayMap<>(102400000);
    @Override
    protected void doGet(HttpServletRequest que, HttpServletResponse pon) {
        super.doGet(que, pon);
        String id = que.getParameter("id");
        String table = que.getParameter("table");
        IdTableQuery key = new IdTableQuery(id, table);
        if(idTableNameMap.containsKey(key)){
            write(pon,idTableNameMap.get(key));
            return;
        }

        if(SharedConstant.AUTO_GENERATE_ID_ENTITY_PREFIX.keySet().stream()
                .map(clz->clz.getSimpleName())
                .anyMatch(clzName->table.replace("Item","").equals(clzName))){
            write(pon,id);
            return;
        }
        try {

            ResultSet rs = DatabaseConnector.preparedStatement("select name from " + table + " where id='" + id + "'").executeQuery();
            if(!rs.next()) return;
            String name = rs.getString("name");
            idTableNameMap.put(key,name);
            write(pon,name);
        } catch (SQLException e) {
            write(pon,e.getMessage());
            e.printStackTrace();
        }
    }
}
class IdTableQuery {
    public String id;
    public String table;


    public IdTableQuery(String id, String table) {
        this.id = id;
        this.table = table;
    }

    @Override
    public boolean equals(Object obj) {
        if(obj instanceof IdTableQuery q){
            return Objects.equals(q.id, this.id) && Objects.equals(q.table, this.table);
        }else
            return false;

    }
}